﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Data.SqlClient;


namespace TinyCinema.Data
{
    public class Actor : Execution
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public ObservableCollection<Movie> Movies { get; set; }
        public Actor() 
        {
            ID = IDGenerate(Tables.Actor);
        }
        public Actor(string _ID)
        {
            ID = _ID;
            PutTableIntoDataSet(Tables.Actor);
            var tbl = ds.Tables[Tables.Actor];
            var Row = tbl.Select(ActorTable.ID + "='" + ID + "'")[0];
            Name = Row[ActorTable.Name] as String;
        }
        public void GetMovies()
        {
            Movies = new ObservableCollection<Movie>();
            PutTableIntoDataSet(Tables.Acting);
            var tbl = ds.Tables[Tables.Acting];
            var Rows = tbl.Select(ActingTable.ActorID + "='" + ID + "'");
            foreach (var Row in Rows)
                Movies.Add(new Movie(Row[ActingTable.MovieID] as String));
        }
        public void Save()
        {
            var tbl = ds.Tables[Tables.Actor];
            if (ID == null)
            {
                try
                {
                    var Row = tbl.Select(ActorTable.Name + "='" + Name + "'")[0];
                    ID = Row[ActorTable.ID] as String;
                    return;
                }
                catch { }

                var NewRow = tbl.NewRow();
                NewRow[ActorTable.ID] = ID;
                NewRow[ActorTable.Name] = Name;
                tbl.Rows.Add(NewRow);

                string sql = "Select * From " + Tables.Actor;
                SqlDataAdapter adapter = new SqlDataAdapter(sql,sqlConnection);
                SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(adapter);
                sqlConnection.Open();
                adapter.Update(tbl);
                sqlConnection.Close();
            }
        }
    }
}
